import datetime
import os
from flask import Flask, request, send_from_directory

app = Flask(__name__)

# 确保上传目录存在
UPLOAD_FOLDER = 'D:/upload'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)


@app.route('/upload', methods=['POST'])
def upload_file():
    # 检查请求中是否包含文件
    if 'file' not in request.files:
        return 'No file part', 400
    file = request.files['file']
    # 检查文件是否有文件名
    if file.filename == '':
        return 'No selected file', 400
    if file:
        # 拼接文件保存路径
        file_path = os.path.join(UPLOAD_FOLDER, file.filename)
        try:
            # 保存文件
            file.save(file_path)
            return 'File uploaded successfully', 200
        except Exception as e:
            return f'Error uploading file: {str(e)}', 500


@app.route('/download/<path:filename>', methods=['GET'])
def download_file(filename):
    try:
        # 从指定目录发送文件
        return send_from_directory(UPLOAD_FOLDER, filename, as_attachment=True)
    except FileNotFoundError:
        return 'File not found', 404


@app.route('/a')
def original_view():
    curtime = datetime.datetime.now()
    datestr = curtime.strftime("%Y-%m-%d %H:%M:%S")
    return datestr


i = 0


@app.route('/b')
def rewritten_view():
    global i
    i = i + 1
    return str(i)


if __name__ == '__main__':
    app.run(debug=True, port=8899)
